package manager.util;

import org.apache.commons.codec.digest.DigestUtils;

public class MD5 {
    public static void main(String[] args) {
        //多次加密
        String pass = "123456";
        String hex = DigestUtils.md5Hex(pass);
        System.out.println(hex);
        hex = DigestUtils.md5Hex(hex);
        System.out.println(hex);

        //盐值加密
        pass = pass + "a";
        hex = DigestUtils.md5Hex(pass);
        System.out.println(hex);

        //多次加密+盐值加密

        //多次加密+多次盐值加密

        //随机加密次数+随机盐值加密
        pass = "123456";
        char[] hex_num = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        int index_count = (int)(Math.random()*hex_num.length);
        //加密次数字符
        char char_count = hex_num[index_count];
        int index_salt = (int)(Math.random()*hex_num.length);
        //盐值加密字符
        char char_salt = hex_num[index_salt];
        String hexpass = pass+char_salt;
        for (int i = 0; i <char_count ; i++) {
            hexpass = DigestUtils.md5Hex(hexpass);
        }
        System.out.println(hexpass);
        System.out.println(char_count+hexpass+char_salt);


    }

    /**
     * 加密函数
     * @param pass
     * @return
     */
    public static String hexpass(String pass){

        char[] hex_num = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        int index_count = (int)(Math.random()*hex_num.length);
        //加密次数字符
        char char_count = hex_num[index_count];
        int index_salt = (int)(Math.random()*hex_num.length);
        //盐值加密字符
        char char_salt = hex_num[index_salt];
        String hexpass = pass+char_salt;
        for (int i = 0; i <char_count ; i++) {
            hexpass = DigestUtils.md5Hex(hexpass);
        }
        return char_count+hexpass+char_salt;
    }

    /**
     * 比较密码   按照一定规则再加密
     * @param parampass
     * @param datapass
     * @return
     */
    public static boolean compare_pass(String parampass,String datapass){
        //次数
        char hex_count = datapass.charAt(0);
        //盐值
        char hex_salt = datapass.charAt(datapass.length()-1);

        String hex_pass = parampass+hex_salt;
        for (int i = 0; i <hex_count ; ++i) {
            hex_pass = DigestUtils.md5Hex(hex_pass);
//            System.out.println(hex_pass);
        }

//        System.out.println(datapass);
        return datapass.equals(hex_count+hex_pass+hex_salt);
    }
}
